<?php

namespace app\api\server\group;

use app\api\model\group\GroupGoodsApiModel;
use app\api\model\group\GroupOrderApiModel;
use app\api\ServerBase;
use app\api\validate\group\GroupOrderVal;
use app\logic\model\user\UserGoodsLogicModel;
use app\logic\model\user\UserLogicModel;
use app\logic\single\GoodsSingle;
use app\logic\single\group\GroupOrderSingle;
use app\logic\single\pay\AliPaySingle;
use app\logic\single\pay\WxPaySingle;
use Snow\Snow;
use think\facade\Db;
use think\facade\Queue;
use think\Request;

class GroupOrderServer extends ServerBase
{

    /**
     * @var array|mixed
     */
    private $param;
    /**
     * @var GroupOrderApiModel
     */
    private $model;
    /**
     * @var GroupGoodsApiModel
     */
    private $goodsModel;
    /**
     * @var GroupOrderVal
     */
    private $validate;

    function __construct(Request $request)
    {
        $this->request=$request;
        $this->param=$request->param();
        $this->model=new GroupOrderApiModel();
        $this->goodsModel = new GroupGoodsApiModel();
        $this->validate = new GroupOrderVal();
    }

    function create(){
        //商品详情购买
        if(!$this->validate->scene('create')->check($this->param)){
            $this->ERROR = $this->validate->getError();
            return false;
        }
        $goods = $this->goodsModel->getFindById($this->param['goods_id']);
        if(empty($goods)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        if(!$this->checkTime($goods)){
            $this->ERROR='未在活动期间，不能购买';
            return false;
        }
        $music_goods = GoodsSingle::getInstance()->getGoods($goods['goods_id'],$goods['type']);
        if(!$this->checkOther($goods,$music_goods)){
            return false;
        }

        if($goods['type'] == 20 || $goods['type'] == 50){
            $sell_id = $music_goods['writer']['id'];
            $writer_rate = $goods['writer_rate']??0;
            if($writer_rate <=0){
                $writer_rate = UserLogicModel::getWriterRate($sell_id);
            }
        }else{
            $sell_id = 0;
            $writer_rate = 0;
        }
        $order=[
            'order_no'=>Snow::createOnlyId(),
            'buyer_id'=>$this->request->user_id,
            'goods_id'=>$goods['id'],
            'music_goods_id'=>$goods['goods_id'],
            'music_goods_type'=>$goods['type'],
            'order_price'=>$goods['price'],
            'pay_price'=>$goods['price'],
            'sell_id'=>$sell_id,
            'writer_price'=> round($goods['price'] * $writer_rate / 100 ,2),
            'writer_rate'=>$writer_rate,
        ];
        Db::startTrans();
        try {
            $this->model->save($order);
            $order_id = $this->model->id;
            Queue::later(600,'app\logic\queue\order_group\Cancel',['order_id'=>$order_id],'order_group_cancel');

            $this->getMessageCode('code_common.success',2);
            Db::commit();
            return $order_id;
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR=$exception->getMessage();
            return false;
        }
    }
    function pay(){
        $id = $this->request->post('id',0);
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //检测订单是否存在
        $order = $this->model->getFindByUserIdAndId($id,$this->request->user_id);
        if(empty($order)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        if($order['status'] != 10){
            $this->ERROR = '该订单不能支付';
            return false;
        }

        $goods = $this->goodsModel->getFindById($order['goods_id']);
        if(empty($goods)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        if(!$this->checkTime($goods)){
            $this->ERROR='未在活动期间，不能购买';
            return false;
        }
        $music_goods = GoodsSingle::getInstance()->getGoods($order['music_goods_id'],$order['music_goods_type']);

        if(!$this->checkOther($goods,$music_goods)){
            return false;
        }
        $terminal = $this->param['terminal']??'h5';
        $data=[];
        //获取名称
        $user = UserLogicModel::getInfoById($order['buyer_id']);
        $order['openid'] = $user['openid'];
        $title = $music_goods['title'];
        //todo 微信支付
        $res= WxPaySingle::getInstance()->pay($order,$terminal,'group',$title);
        $data['wx_'.$terminal] = $res;
        //支付宝支付
        $res= AliPaySingle::getInstance()->pay($order,$terminal,'group',$title,$this->param['ali_quit_url']??'',$this->param['ali_return_url']??'');
        $data['ali_'.$terminal] = $res;
        return $data;
    }
    private function checkTime($goods): bool
    {
        //5  7  9
        if($goods['start_time'] > date('Y-m-d H:i:s') || $goods['end_time'] < date('Y-m-d H:i:s')){
            return false;
        }
        return true;
    }
    private function checkOther($goods,$music_goods){
        if($goods['is_complete'] != 10){
            $this->ERROR='拼团已结束，不能购买';
            return false;
        }
        if($this->model->isBuy($goods['id'],$this->request->user_id)){
            $this->ERROR='请勿重复购买';
            return false;
        }
        if($music_goods['title'] == '已删除'){
            $this->ERROR='音乐已删除，不能购买';
            return false;
        }
        if(UserGoodsLogicModel::isHave($goods['goods_id'],$goods['type'],$this->request->user_id)){
            $this->ERROR = '已拥有商品'.$goods['title'];
            return false;
        }
        return true;
    }

    function refund(){
        $id =  $this->request->param('id');
        $info = $this->model->getFindByUserIdAndId($id,$this->request->user_id);
        if(empty($info)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        if($info['status'] != 20){
            $this->ERROR='该订单不能申请退款';
        }
        $res = GroupOrderSingle::getInstance()->apply_refund($id);
    }
    public function myList(){
        [$page,$limit] = $this->getPage($this->param);
        $field='id,order_no,status,create_time,music_goods_id,music_goods_type,order_price';
        $this->param['buyer_id'] = $this->request->user_id;
        [$list,$count] = $this->model->getApiList($this->param,[],$field,$page,$limit);
        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }
    function myDetail(){
        $id =  $this->request->param('id');
        $info = $this->model->getFindByUserIdAndId($id,$this->request->user_id,'id,order_no,status,create_time,goods_id,music_goods_id,music_goods_type,order_price');
        if(empty($info)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        $info['goods'] = GroupGoodsApiModel::where('id',$info['goods_id'])
            ->field('id,title,img,goods_id,type,num,complete_num,end_time')
            ->find();
        $info['goods']['num'] = GroupOrderApiModel::getApiBuyNum($info['goods']);
        $this->getMessageCode('adminMessage.success.select',2);
        return $info;
    }
}